<?php

namespace Common\Logic;

/**
 * 货币逻辑
 * @modify wenhui 2018-01-30 创建
 */
class CurrencyLogic extends \Common\Controller\BaseController {

    /**
     * 获取货币列表
     * @modify wenhui 2018-01-30 创建
     * @return array
     */
    public function getBpCurrency($hotelId = null) {
        $currencyModel = D('Currency');
        $currencyData = $currencyModel->getCurrencyInfo();

        if (!is_null($hotelId)) {
            $currencyHotelModel = D('CurrencyHotel');
            $hotelDefaultCurrency = $this->takeHotelCurrency($hotelId, true);
            $hotelDefaultCurrency = array_values($hotelDefaultCurrency);
            if (empty($hotelDefaultCurrency)) {
                $hotelDefaultCurrency[0]['currencyId'] = 8; // 人民币
            }

            foreach ($currencyData as $key => &$currency) {
                if ($currency['id'] != $hotelDefaultCurrency[0]['currencyId']) {
                    $currency['type'] = 0;
                } else {
                    $currency['type'] = 1;
                }
            }
            unset($currency);
        }

        foreach ($currencyData as $key => &$currency) {
           switch (LANG_SET) {
                case 'zh_tw':
                    $currency['name'] = $currency['twname'];
                    break;
                case 'en_us':
                    $currency['name'] = $currency['usname'];
                    break;
            }
        }

        return $currencyData;
    }

    /**
     * 获取货币列表
     * @modify wenhui 2018-01-30 创建
     * @return array
     */
    public function getBpCurrencyAndDefault($hotelId) {
        $currencyModel = D('Currency');
        $currencyData = $currencyModel->getCurrencyInfo();

        if (!is_null($hotelId)) {
            $currencyHotelModel = D('CurrencyHotel');
            $hotelDefaultCurrency = $this->takeHotelCurrency($hotelId, true);
            $hotelDefaultCurrency = array_values($hotelDefaultCurrency);
            if (!empty($hotelDefaultCurrency)) {
                foreach ($currencyData as $key => &$currency) {
                    if ($currency['id'] != $hotelDefaultCurrency[0]['currencyId']) {
                        $currency['type'] = 0;
                    } else {
                        $currency['type'] = 1;
                    }
                }
                unset($currency);
            } else {
                foreach ($currencyData as $key => &$currency) {
                    $currency['type'] = 0;
                }
                unset($currency);
            }
        }

        foreach ($currencyData as $key => &$currency) {
           switch (LANG_SET) {
                case 'zh_tw':
                    $currency['name'] = $currency['twname'];
                    break;
                case 'en_us':
                    $currency['name'] = $currency['usname'];
                    break;
            }
        }

        return $currencyData;
    }

    /**
     * 获取客栈货币
     * @modify wenhui 2018-01-30 创建
     * @param  integer   $hotelId    客栈id
     * @param  bool   $defaultCurrency    获取默认货币
     */
    public function takeHotelCurrency($hotelId, $defaultCurrency = false, $LangSet = null) {
        $currencyHotelModel = D('CurrencyHotel');

        $bpCurrency = $this->getBpCurrency();
        $bpCurrency = getArrayValueAsIndex($bpCurrency, 'id');
        $hotelCurrency = $currencyHotelModel->getHotelCurrencyByHotel($hotelId);

        $LangSet = !is_null($LangSet) ? $LangSet : LANG_SET;
        if (!empty($hotelCurrency)) {
            foreach ($hotelCurrency as $key => &$currency) {
                if ($defaultCurrency) {
                    if ($currency['type'] != 1) {
                        unset($hotelCurrency[$key]);
                        continue;
                    }
                }

                if ($LangSet == 'en_us') {
                    $currency['name'] =  $bpCurrency[$currency['currency_id']]['usname'] . ' (' .  $bpCurrency[$currency['currency_id']]['symbol'] . ')';
                } else if ($LangSet == 'zh_tw') {
                    $currency['name'] =  $bpCurrency[$currency['currency_id']]['twname'] . ' (' .  $bpCurrency[$currency['currency_id']]['symbol'] . ')';
                } else {
                    $currency['name'] =  $bpCurrency[$currency['currency_id']]['name'] . ' (' .  $bpCurrency[$currency['currency_id']]['symbol'] . ')';
                }

                $currency['hotelCurrencyId'] = $currency['id'];
                $currency['currencyId'] = $currency['currency_id'];
                $currency['standSymbol'] = $bpCurrency[$currency['currency_id']]['standsymbol'];
                $currency['symbol'] = $bpCurrency[$currency['currency_id']]['symbol'];

                unset($currency['currency_id']);
                unset($currency['hotelentity_id']);
                unset($currency['id']);
                unset($currency['isdelete']);
            }
        }

        $hotelCurrency = array_values($hotelCurrency);
        return $hotelCurrency;
    }

    /**
     * 保存客栈默认货币 或 是否提示设置默认货币 即 $currencyId = null
     * @modify wenhui 2018-01-30 创建
     * @param  integer   $currentHotelId  当前客栈id
     * @param  integer   $currencyId  货币id
     * @param  integer   $type  1=不可删除 0=可删除
     */
    public function addUserHotelDefaultCurrency($currentHotelId, $currencyId, $type) {
        $currencyHotelModel = D('CurrencyHotel');

        $isSetDefaultCurrency = false;
        if (!is_null($currencyId)) {
            $userId = getUserId();
            // 获取用户管理客栈id
            $AdminHotelModel = D('AdminHotel');
            $adminHotelInfo = $AdminHotelModel->getInfosByAdmin($userId);
            $hotelIds = array_column($adminHotelInfo, 'hotelentity_id');

            $hotelCurrency = $currencyHotelModel->getAllHotelCurrency($hotelIds, $currencyId, true);
            $hotelCurrency = getArrayValueAsIndex($hotelCurrency, 'hotelentity_id');

            $addCurrenInfo = array();
            foreach ($hotelIds as $key => $hotelId) {
                // 客栈是否已设置默认
                $defaultCurrency = $currencyHotelModel->getDefaultCurrency($hotelId);
                if (!empty($defaultCurrency)) {
                    continue;
                }
                if (isset($hotelCurrency[$hotelId])) {
                    $saveResult = $currencyHotelModel->saveHotelCurrencyByHotelAndcuId($hotelId, $currencyId, NOT_DELETE, $type);
                    if ($saveResult === false) {
                        throw new \Exception('500,508', 508);
                        return false;
                    }
                } else {
                    $addCurrenInfo[] = array(
                        'hotelentity_id' => $hotelId,
                        'currency_id' => $currencyId,
                        'type' => $type,
                    );
                }
            }

            if (!empty($addCurrenInfo)) {
                $addResult = $currencyHotelModel->addAll($addCurrenInfo);
                if (empty($addResult)) {
                    throw new \Exception('500,508', 508);
                    return false;
                }
            }

            $isSetDefaultCurrency = true;
        } else {
            $defaultCurrency = $currencyHotelModel->getDefaultCurrency($currentHotelId);
            $isSetDefaultCurrency = !empty($defaultCurrency) ? true : false;
        }

        return $isSetDefaultCurrency;
    }

    /**
     * 添加客栈货币
     * @modify wenhui 2018-01-30 创建
     * @param  integer   $hotelId    客栈id
     * @param  integer   $currencyId  货币id
     * @param  integer   $type  1=不可删除 0=可删除
     */
    public function addHotelCurrency($hotelId, $currencyId, $type) {
        $currencyHotelModel = D('CurrencyHotel');

        $hotelCurrency = $currencyHotelModel->getHotelCurrency($hotelId, $currencyId, true);
        if (!empty($hotelCurrency)) {
            if ($hotelCurrency['isdelete'] != IS_DELETE) {
                throw new \Exception('403,516', 516);
                return false;
            } else {
                $saveResult = $currencyHotelModel->saveHotelCurrencyByHotelAndcuId($hotelId, $currencyId, NOT_DELETE);
                if ($saveResult === false) {
                    throw new \Exception('500,508', 508);
                    return false;
                }
                return true;
            }
        }

        $hotelCurrency = $currencyHotelModel->getHotelCurrencyByHotel($hotelId);
        if (count($hotelCurrency) >= MAX_RESOURCE_COUNT) {
            throw new \Exception('403,406', 406);
            return false;
        }

        $addResult = $currencyHotelModel->addHotelCurrency($hotelId, $currencyId, $type);
        if ($addResult === false) {
            throw new \Exception('500,508', 508);
            return false;
        }
        
        return $addResult;
    }

    /**
     * 修改客栈货币
     * @modify wenhui 2018-01-30 创建
     * @param  integer   $currencyId  货币id
     * @param  integer   $hotelCurrencyId  客栈货币id
     * @param  integer   $isDelete      0=启用1=删除
     */
    public function saveHotelCurrency($hotelCurrencyId, $currencyId = null, $isDelete = null) {
        $currencyHotelModel = D('CurrencyHotel');

        // 是否已删除
        $hotelCurrency = $currencyHotelModel->getInfoByHotelCurrencyId($hotelCurrencyId);
        if (empty($hotelCurrency)) {
            throw new \Exception('500,515', 515);
            return false;
        }

        $saveResult = $currencyHotelModel->saveHotelCurrencyById($hotelCurrencyId, $currencyId, $isDelete);
        if ($saveResult === false) {
            throw new \Exception('500,506', 506);
            return false;
        }
        
        return true;
    }

    /**
     * 价格汇率转换 || 获取转换前货币与转换后货币的汇率值 并添加
     * @modify wenhui 2018-02-01    创建
     * @param intetger $currencyId 转换前货币id
     * @param intetger $transCurrencyId 转换后货币id
     * @param array | decimal $priceData    decimal | 一维数组 | 二维数组
     * @return mix index 数组键名
     */
    public function exchangeRates ($currencyId, $transCurrencyId, $priceData, $index = null) {
        $currencyExchangeRateModel = D('CurrencyExchangeRate');

        // 检查是否存在汇率值
        $currencyExchangeRate = $currencyExchangeRateModel->checkTransRateExist($currencyId, $transCurrencyId);

        $currencyLogic = A('Common/Currency', 'Logic');
        // 系统货币
        $bpCurrency = $currencyLogic->getBpCurrency();
        $bpCurrency = getArrayValueAsIndex($bpCurrency, 'id');
        $standsymbol = $bpCurrency[$currencyId]['standsymbol'];
        $transStandsymbol = $bpCurrency[$transCurrencyId]['standsymbol'];
        if (empty($currencyExchangeRate)) {
            //  获取 转换前货币 与 转换后货币的汇率值 并添加
            $rateValue = getRateValue($standsymbol, $transStandsymbol);
            if ($rateValue !== false && is_numeric($rateValue)) {
                $addResult = $currencyExchangeRateModel->addCurrencyRate($currencyId, $transCurrencyId, $rateValue);
            }
        } else {
            // 一天更新一次汇率值
            if (date('Y-m-d', strtotime($currencyExchangeRate['updatetime'])) != date('Y-m-d')) {
                $rateValue = getRateValue($standsymbol, $transStandsymbol);
                if ($rateValue !== false && is_numeric($rateValue)) {
                    $saveResult = $currencyExchangeRateModel->saveCurrencyRate($currencyId, $transCurrencyId, $rateValue);
                } else {
                    $rate = true;
                }
            } else {
                $rate = true;
            }
        }

        if ($rate) {
            $rateValue = $currencyExchangeRate['rare_value'];
        }

        if (empty($priceData)) {
            return $rateValue;
        }

        if ($rateValue !== false && is_numeric($rateValue)) {
            $priceData = exchangeRateConversion($priceData, $rateValue, $index);
        }

        return $priceData;
    }
}